package com.gjzt.business.media.service;

import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.UUID;

import com.eastdigit.system.model.BusinessException;
import com.eastdigit.system.model.SqlBuilder;
import com.eastdigit.util.FileUtil;
import com.eastdigit.util.PropertiesUtil;
import com.gjzt.business.media.inter.MediaEquipmentMapper;
import com.gjzt.business.media.inter.MediaResourceMapper;
import com.gjzt.business.media.model.MediaEquipment;
import com.gjzt.business.utils.Constant;
import com.gjzt.business.utils.QRCodeUtil;
import com.google.zxing.WriterException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eastdigit.servlet.ReqBean;
import com.eastdigit.system.service.BaseService;
import com.eastdigit.util.DateUtil;
import com.eastdigit.util.StringUtil;
import com.gjzt.business.media.inter.MediaStopMapper;
import com.gjzt.business.media.model.MediaStop;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class MediaStopService extends BaseService {

    @Autowired
    private MediaResourceMarksService mediaResourceMarksService;

    @Autowired
    private MediaStopMapper mediaStopMapper;

    @Autowired
    private MediaResourceService mediaResourceService;

    @Autowired
    private MediaEquipmentMapper equipmentMapper;

    @Autowired
    private MediaTypeService mediaTypeService;

    @Autowired
    private MediaResourceMapper mediaResourceMapper;

    public static final String ATTACHMENT_PATH = PropertiesUtil.getProperty("attachment.path");

    public static final String QRCODE_PATH = PropertiesUtil.getProperty("qrcode.path");

    /**
     * 查询
     * 
     * @param reqBean
     * @return
     */
    public JSONObject findMediaStop(ReqBean reqBean) {
        StringBuffer sql = new StringBuffer("select b.*,b.STOP_ID itemId from MEDIA_STOP b where 1 = 1 ");
        if (!StringUtil.isEmpty(reqBean.getInfo("stopName"))) {
            sql.append(" and b.STOP_NAME like '%").append(reqBean.getInfo("stopName")).append("%'");
        }
        if (!StringUtil.isEmpty(reqBean.getInfo("roadName"))) {
            sql.append(" and b.ROAD_NAME like '%").append(reqBean.getInfo("roadName")).append("%'");
        }
        if (!StringUtil.isEmpty(reqBean.getInfo("province"))) {
            sql.append(" and b.PROVINCE = '").append(reqBean.getInfo("province")).append("'");
        }
        if (!StringUtil.isEmpty(reqBean.getInfo("city"))) {
            sql.append(" and b.CITY = '").append(reqBean.getInfo("city")).append("'");
        }
        if (!StringUtil.isEmpty(reqBean.getInfo("county"))) {
            sql.append(" and b.COUNTY = '").append(reqBean.getInfo("county")).append("'");
        }
        if (!StringUtil.isEmpty(reqBean.getInfo("direction"))) {
            sql.append(" and b.DIRECTION = '").append(reqBean.getInfo("direction")).append("'");
        }
        if (!StringUtil.isEmpty(reqBean.getInfo("status"))) {
            sql.append(" and b.STATUS = '").append(reqBean.getInfo("status")).append("'");
        }
        sql.append(" order by b.STOP_NAME ");
        JSONObject returnJson = this.queryTable(sql.toString(), null, reqBean.getPageSize(), reqBean.getPageIndex());

        reqBean.addInfo("parentId", Constant.MEDIA_TYPE_STOP);
        JSONArray mediaTypes = mediaTypeService.getMediaTypesByParentId(reqBean);
        JSONArray dataList = returnJson.getJSONArray("rows");
        if (dataList != null && dataList.size() > 0) {
            for (int i = 0; i < dataList.size(); i++) {
                JSONObject o = dataList.getJSONObject(i);
                String stopId = o.getString("stopId");
                o.put("zgEquipments", getEquipmentCount("2", stopId));
                o.put("hctEquipments", getEquipmentCount("1", stopId));
                for (int j = 0; j < mediaTypes.size(); j++) {
                    JSONObject temp = mediaTypes.getJSONObject(j);
                    String mediaType = temp.getString("mediaId");
                    o.put("count" + mediaType, mediaResourceMapper.selectCountByStopIdAndMeidaType(stopId, mediaType));
                }
            }
        }
        return returnJson;

    }

    public JSONObject getMediaStopInfo(String stopId) {
        StringBuffer sql = new StringBuffer("select * from MEDIA_STOP s");
        sql.append(" where s.STOP_ID = '").append(stopId).append("'");
        JSONArray _l = this.query(sql.toString());
        return (_l == null || _l.isEmpty()) ? null : _l.getJSONObject(0);
    }

    public JSONObject getMediaStopInfoWithRes(String stopId) {
        JSONObject returnJson = new JSONObject();
        JSONObject stopInfo = getMediaStopInfo(stopId);
        JSONArray stopResources = mediaResourceService.findBusMediaResources(stopId);
        returnJson.put("stopInfo", stopInfo);
        returnJson.put("stopResources", stopResources);
        return returnJson;
    }

    private int getEquipmentCount(String equipmentType, String stopId) {
        String sql = "";
        if (equipmentType.equals("1")) { // 候车亭
            sql = "select count(1) FROM MEDIA_EQUIPMENT a where a.STOP_ID = '" + stopId + "' "
                    + "AND (a.EQUIPMENT_TYPE = '候车亭大板' or a.EQUIPMENT_TYPE = '候车亭小板' or a.EQUIPMENT_TYPE = '候车亭LED')";
        } else if (equipmentType.equals("2")) {
            sql = "select count(1) FROM MEDIA_EQUIPMENT a where a.STOP_ID = '" + stopId + "' "
                    + "AND a.EQUIPMENT_TYPE = '站杆'";
        }
        return executeInt(sql);
    }

    /**
     * 新增
     * 
     * @param reqBean
     */
    public void saveMediaStop(ReqBean reqBean) {
        MediaStop mediaStop = getMediaStop(reqBean);

        mediaStop.setOperator(reqBean.getUserId());
        mediaStop.setModifyTime(new Date());

        if (StringUtil.isEmpty(mediaStop.getStopId())) {
            mediaStop.setStopId(stringId());
            mediaStop.setMakeTime(new Date());
            mediaStopMapper.insert(mediaStop);

            if (reqBean.containsKey("stopMarks")) {
                String markIdsStr = reqBean.getInfo("stopMarks");
                JSONArray markIds = JSONArray.fromObject(markIdsStr);
                for (Object markId : markIds) {
                    mediaResourceMarksService.createStopMark(markId.toString(), mediaStop.getStopId());
                }
            }
        } else {
            mediaStopMapper.updateByPrimaryKeySelective(mediaStop);

            if (reqBean.containsKey("stopMarks")) {
                mediaResourceMarksService.removeMarksOfStop(mediaStop.getStopId());
                String markIdsStr = reqBean.getInfo("stopMarks");
                JSONArray markIds = JSONArray.fromObject(markIdsStr);
                for (Object markId : markIds) {
                    mediaResourceMarksService.createStopMark(markId.toString(), mediaStop.getStopId());
                }
            }
        }
    }

    public MediaStop getMediaStop(String stopId) {
        return mediaStopMapper.selectByPrimaryKey(stopId);
    }

    /**
     * 从表单获取对象
     * 
     * @param reqBean
     * @return
     */
    private MediaStop getMediaStop(ReqBean reqBean) {
        MediaStop mediaStop = new MediaStop();

        mediaStop.setStopId(reqBean.getInfo("stopId"));
        mediaStop.setStopCode(reqBean.getInfo("stopCode"));
        mediaStop.setStopName(reqBean.getInfo("stopName"));
        mediaStop.setStopNo(reqBean.getInfo("stopNo"));
        mediaStop.setLongitude(reqBean.getInfo("longitude"));
        mediaStop.setLatitude(reqBean.getInfo("latitude"));
        mediaStop.setStatus(reqBean.getInfo("status"));
        mediaStop.setDirection(reqBean.getInfo("direction"));
        mediaStop.setRoadName(reqBean.getInfo("roadName"));
        mediaStop.setStopImg(reqBean.getInfo("stopImg"));
        mediaStop.setProvince(reqBean.getInfo("province"));
        mediaStop.setCity(reqBean.getInfo("city"));
        mediaStop.setCounty(reqBean.getInfo("county"));

        mediaStop.setZpjdSituation(reqBean.getInfo("zpjdSituation"));
        mediaStop.setDeputyStopName(reqBean.getInfo("deputyStopName"));
        mediaStop.setPassLines(reqBean.getInfo("passLines"));
        mediaStop.setMaintenanceCompany(reqBean.getInfo("maintenanceCompany"));
        mediaStop.setZgStyle(reqBean.getInfo("zgStyle"));
        mediaStop.setHctssType(reqBean.getInfo("hctssType"));
        mediaStop.setLdSituation(reqBean.getInfo("ldSituation"));
        mediaStop.setOperator(reqBean.getUserId());
        mediaStop.setMakeTime(DateUtil.parseDateTime(reqBean.getInfo("makeTime")));
        mediaStop.setModifyTime(new Date());
        mediaStop.setRemark(reqBean.getInfo("remark"));

        return mediaStop;
    }

    public JSONObject equipment(ReqBean reqBean) {

        String stopId = reqBean.getInfo("stopId");
        String queryType = reqBean.getInfo("queryType");
        if (StringUtils.isBlank(stopId) || StringUtils.isBlank(queryType)) {
            throw new BusinessException("缺少参数!");
        }
        String sql = "";
        if ("1".equals(queryType)) { // 候车亭
            sql = "select * FROM MEDIA_EQUIPMENT a where a.STOP_ID = '" + stopId
                    + "' AND (a.EQUIPMENT_TYPE = '候车亭大板' or a.EQUIPMENT_TYPE = '候车亭小板' or a.EQUIPMENT_TYPE = '候车亭LED')";
        } else {
            sql = "select * FROM MEDIA_EQUIPMENT a where a.STOP_ID = '" + stopId + "' AND a.EQUIPMENT_TYPE = '站杆'";
        }
        return queryTable(new SqlBuilder(sql), reqBean.getPageSize(), reqBean.getPageIndex());
    }

    public void equipmentAdd(ReqBean reqBean) {

        MediaEquipment equipment = getMediaEquipment(reqBean);
        equipment.setEquipmentId(UUID.randomUUID() + "");
        equipment.setMakeTime(new Date());
        equipment.setModifyTime(new Date());
        equipment.setOperator(reqBean.getUserId());
        equipmentMapper.insert(equipment);
    }

    private MediaEquipment getMediaEquipment(ReqBean reqBean) {

        MediaEquipment equipment = new MediaEquipment();

        equipment.setEquipmentId(reqBean.getInfo("equipmentId"));
        equipment.setEquipmentCode(reqBean.getInfo("equipmentCode"));
        equipment.setStopId(reqBean.getInfo("stopId"));
        equipment.setEquipmentType(reqBean.getInfo("equipmentType"));
        equipment.setConstructionYear(reqBean.getInfo("constructionYear"));
        equipment.setCreateCompany(reqBean.getInfo("createCompany"));
        equipment.setRemovalCount(reqBean.getInfo("removalCount"));
        equipment.setFootDepth(reqBean.getInfo("footDepth"));
        equipment.setPowerSource(reqBean.getInfo("powerSource"));
        equipment.setPowerSourceApply(reqBean.getInfo("powerSourceApply"));
        equipment.setSubstation(reqBean.getInfo("substation"));
        equipment.setLighting(reqBean.getInfo("lighting"));
        equipment.setInternalStructure(reqBean.getInfo("internalStructure"));
        equipment.setElectricalEquipment(reqBean.getInfo("electricalEquipment"));
        equipment.setElectricUpdateTime(DateUtil.parseDateTime(reqBean.getInfo("electricUpdateTime")));
        equipment.setBillboardRepairTime(DateUtil.parseDateTime(reqBean.getInfo("billboardRepairTime")));
        equipment.setStructureRemainingYear(reqBean.getInfo("structureRemainingYear"));
        equipment.setAssessDept(reqBean.getInfo("assessDept"));

        return equipment;
    }

    public void equipmentUpdate(ReqBean reqBean) {
        MediaEquipment equipment = getMediaEquipment(reqBean);
        equipment.setMakeTime(new Date());
        equipment.setModifyTime(new Date());
        equipment.setOperator(reqBean.getUserId());
        equipmentMapper.updateByPrimaryKey(equipment);
    }

    public void equipmentDelete(ReqBean reqBean) {
        String equipmentId = reqBean.getInfo("equipmentId");
        if (StringUtils.isBlank(equipmentId)) {
            throw new BusinessException("缺少参数!");
        }

        equipmentMapper.deleteByPrimaryKey(equipmentId);
    }

    public JSONArray selectStopEquipments(ReqBean reqBean) {
        String stopId = reqBean.getInfo("stopId");
        if (StringUtils.isBlank(stopId)) {
            throw new BusinessException("缺少站点主键!");
        }
        String sql = "select a.EQUIPMENT_ID value, CONCAT(a.EQUIPMENT_CODE,'-',a.EQUIPMENT_TYPE) name "
                + "FROM MEDIA_EQUIPMENT a where a.STOP_ID = '" + stopId + "'";

        return query(sql);
    }

    public void dealQrCode(ReqBean reqBean, HttpServletRequest request, HttpServletResponse response)
            throws IOException, WriterException {
        String stopId = reqBean.getInfo("stopId");
        String stopNo = reqBean.getInfo("stopNo");
        if (StringUtils.isBlank(stopId) || StringUtils.isBlank(stopNo)) {
            throw new BusinessException("非法请求!");
        }

        File file = new File(ATTACHMENT_PATH + QRCODE_PATH);
        if (!file.exists()) {
            file.mkdir();
        }
        String path = ATTACHMENT_PATH + QRCODE_PATH;
        File tempFile = new File(path + stopId + ".png");
        if (!tempFile.exists()) {
            QRCodeUtil.zxingCodeCreate(stopId, 1000, 1000, path + stopId + Constant.QRCODE_IMG_TYPE_PNG, "png");
        }
        downLoadImg(path + stopId + ".png", stopNo, request, response);
    }

    public void downLoadImg(String path, String stopNo, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.reset();
        response.setContentType("text/html;charset=utf-8");
        String filename = URLEncoder.encode("二维码-" + stopNo + ".png", "UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);
        FileInputStream fis = new FileInputStream(path);
        byte buff[] = new byte[2048];
        int len = 0;
        OutputStream os = response.getOutputStream();
        while((len = fis.read(buff))>0){
            os.write(buff, 0, len);
        }
        os.close();
        fis.close();
    }
}